import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class SinhVienService {
	private ArrayList<SinhVien> listSinhVien;

	public SinhVienService() {
		super();
		listSinhVien = new ArrayList<SinhVien>();
	}

	public int them(SinhVien sv) {
		listSinhVien.add(sv);
		return listSinhVien.size();
	}

	public int xoa(SinhVien sv) {
		listSinhVien.remove(sv);
		return listSinhVien.size();
	}

	public boolean saveToFile(FileOutputStream file) {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(file);
			oos.writeObject(listSinhVien);
			oos.close();
		} catch (IOException ex) {
			System.err.println("io error");
			return false;
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	public boolean loadFromFile(FileInputStream file) {
		try {
			ObjectInputStream oos = new ObjectInputStream(file);
			listSinhVien = (ArrayList<SinhVien>) oos.readObject();
			oos.close();
		} catch (IOException | ClassNotFoundException ex) {
			System.err.println("io error");
		}
		return true;
	}

	@Override
	public String toString() {
		String str = "";
		for (SinhVien sv : listSinhVien) {
			str += "\n" + sv.toString();
		}
		return str;
	}
}
